<template>
  <BaseDialog
    :visible="visible"
    title="修改设备名称"
    width="400px"
    :confirm-loading="loading"
    @close="handleClose"
    @cancel="handleClose"
    @confirm="handleConfirm"
    @update:visible="handleUpdateVisible"
  >
    <div class="edit-camera-name-dialog">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        @submit.prevent
      >
        <el-form-item label="设备名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入设备名称"
            maxlength="50"
            show-word-limit
            clearable
            @keyup.enter="handleConfirm"
          />
        </el-form-item>
      </el-form>
    </div>
  </BaseDialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick } from 'vue'
import { ElForm, ElFormItem, ElInput } from 'element-plus'
import BaseDialog from '@/components/BaseDialog.vue'
import { updateDeviceName } from '@/api/device'
import { success, error } from '@/utils/toast'

// Props
interface Props {
  visible: boolean
  cameraData: {
    id: number
    name: string
  } | null
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:visible': [visible: boolean]
  'close': []
  'success': [cameraId: number, newName: string]
}>()

// 响应式数据
const formRef = ref()
const loading = ref(false)

// 表单数据
const form = reactive({
  name: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
    { min: 1, max: 50, message: '设备名称长度在 1 到 50 个字符', trigger: 'blur' }
  ]
}

// 监听弹框显示状态，重置表单
watch(() => props.visible, (newVisible) => {
  if (newVisible && props.cameraData) {
    form.name = props.cameraData.name
    // 重置表单验证状态
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }
})

// 处理关闭
const handleClose = () => {
  emit('update:visible', false)
  emit('close')
}

// 处理更新visible
const handleUpdateVisible = (visible: boolean) => {
  emit('update:visible', visible)
}

// 处理确认
const handleConfirm = async () => {
  if (!formRef.value || !props.cameraData) return
  
  try {
    // 表单验证
    await formRef.value.validate()
    
    // 检查名称是否发生变化
    if (form.name === props.cameraData.name) {
      error('设备名称未发生变化')
      return
    }
    
    loading.value = true
    
    // 调用API更新设备名称
    await updateDeviceName(props.cameraData.id, form.name)
    
    success('设备名称修改成功')
    
    // 触发成功事件
    emit('success', props.cameraData.id, form.name)
    
    // 关闭弹框
    handleClose()
  } catch (err) {
    console.error('修改设备名称失败:', err)
    error('修改设备名称失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.edit-camera-name-dialog {
  padding: 20px 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__inner) {
  font-size: 14px;
}
</style>
